package data

import (
	"errors"
	"fmt"
	"manage/app/exam/internal/biz"
	"strings"
	"time"

	"github.com/Fromsko/gouitls/auth"
	"github.com/Fromsko/gouitls/logs"
	"github.com/go-kratos/kratos/v2/log"
	"gorm.io/gorm"
)

var echo = logs.InitLogger()

type examRepo struct {
	data *Data
	log  *log.Helper
}

func NewExamRepoRepo(data *Data, logger log.Logger) biz.ExamRepo {
	c := &examRepo{
		data: data,
		log:  log.NewHelper(logger),
	}
	c.Setup()
	return c
}

// Setup 初始化
func (u *examRepo) Setup() {

	func(db *gorm.DB) {
		if db.Migrator().HasTable(biz.Exam{}) {
			echo.Warn("考试表已存在, 跳过创建。")
			return
		}

		if err := db.AutoMigrate(biz.Exam{}); err != nil {
			echo.Errorf("创建表失败：%v", err)
		}

		echo.Info("考试表创建完成")
	}(u.data.Mysql)

}

func CheckExam(db *gorm.DB, examID string) (*biz.Exam, error) {

	var result biz.Exam
	if err := db.Where("exam_id = ?", examID).First(&result); err.Error == gorm.ErrRecordNotFound {
		return &result, nil
	}
	return &result, fmt.Errorf("考试已经存在")
}

// TODO: 创建考试
func (repo *examRepo) CreateExam(req *biz.CreateRequest) (resp *biz.CreateResponse, err error) {

	t := time.Now()
	newExam := &biz.Exam{
		ExamName:    req.ExamName,
		ExamTime:    req.ExamTime,
		ExamContent: req.ExamContent,
		TeacherID:   req.TeacherID,
		ExamID:      strings.Split(auth.GenUUID(req.ExamName), "-")[4],
		CreatedAt:   t,
		UpdatedAt:   t,
	}

	resp = &biz.CreateResponse{}
	resp.Message = "考试创建成功"
	resp.ExamID = newExam.ExamID

	// NOTE: 是否存在考试
	if _, err = CheckExam(repo.data.Mysql, newExam.ExamID); err != nil {
		resp.Message = err.Error()
		return resp, err
	}

	// NOTE: 考试不存在 => 创建考试
	if err = repo.data.Mysql.Create(newExam).Error; err != nil {
		resp.Message = err.Error()
		return resp, err
	}
	return resp, nil
}

// TODO: 删除考试
func (repo *examRepo) DeleteExam(examID string) error {

	if _, err := CheckExam(repo.data.Mysql, examID); err == nil {
		return errors.New("考试不存在")
	}

	err := repo.data.Mysql.Where("exam_id = ?", examID).Delete(&biz.Exam{}).Error
	if err != nil {
		return err
	}
	return nil
}

// TODO: 修改考试
func (repo *examRepo) UpdateExam(request *biz.Exam) error {

	// 先查询考试是否存在
	exam, err := CheckExam(repo.data.Mysql, request.ExamID)
	if err == nil {
		return errors.New("考试不存在")
	}

	request.ExamName = exam.ExamName
	request.CreatedAt = exam.CreatedAt

	// 更新考试信息
	if err := repo.data.Mysql.Where("exam_id = ?", request.ExamID).Save(&request).Error; err != nil {
		return err
	}

	return nil
}

// TODO: 查询考试
func (repo *examRepo) GetExamInfo(examID string) (*biz.Exam, error) {

	// 先查询考试是否存在
	resp, err := CheckExam(repo.data.Mysql, examID)
	if err == nil {
		return nil, errors.New("考试不存在")
	}
	return resp, nil
}
